import forms, models, uuid

from django.conf import settings
from django.core.urlresolvers import reverse
from django.shortcuts import render, render_to_response, redirect
from django.template import RequestContext
from django.db import transaction
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.generic import ListView, DetailView
from paypal.standard.forms import PayPalPaymentsForm

class ServiceRequestListView(ListView):
    model = models.ServiceRequest
    template_name ='agent/agent_cabinet_index.html'
    context_object_name = 'sr_list'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(ServiceRequestListView, self).get_context_data(**kwargs)
        # Add in the status choices
        context['status_choice'] = models.REQUEST_STATUS_CHOICES
        
        return context

class ServiceRequestDetailView(DetailView):
    model = models.ServiceRequest
    template_name = 'request_detail.html'
    context_object_name = 'sr'
    slug_field = 'reference_key'


def request_status(request, reference_key):
    service_request = models.ServiceRequest.objects.get_by_reference_key(reference_key)
    if not service_request:
        return redirect('request_not_found')
    
    return render_to_response("request_status.html", {'title': 'CAIPS request status information',
                                                      'service_request': service_request},
                              context_instance=RequestContext(request))

@never_cache
@csrf_protect
@transaction.commit_on_success
def make_initial_request(request):
    if request.method == 'POST':
        sr_form = forms.InitialServiceRequestForm(request.POST, prefix='sr')
        principal_form = forms.ApplicantFormInitial(request.POST, prefix='principal')
        dependents_formset = forms.ApplicantFormInitialFormSet(request.POST, queryset=models.Applicant.objects.none(), prefix='dependents')
        
        if dependents_formset.is_valid() and sr_form.is_valid() and principal_form.is_valid():
            # Save data
            sr = models.ServiceRequest.objects.create_initial_request(request.user, 
                                                                      sr_form.cleaned_data['email'],
                                                                      sr_form.cleaned_data['visa_office'],
                                                                      sr_form.cleaned_data['file_no'])
            # Add principal applicant
            app = principal_form.save(commit=False)
            app.request = sr
            app.is_principal = True
            app.save()
            
            # Add dependents if any
            for dependent_form in dependents_formset:
                dep = dependent_form.save(commit=False)
                dep.request = sr
                dep.is_principal = False
                dep.save()
            
            # TODO: remove. test only
            ##############################
            #app.pk = None
            #app.save()
            
            #response = HttpResponse(mimetype='application/pdf')
            #response['Content-Disposition'] = 'attachment; filename=IMM5475e.pdf'
            #buff = sr.generate_consent_forms(send_email=True)
            #response.write(buff)
            
            #return response
            ##############################
            
            sr.generate_consent_forms(send_email=True)

            return redirect('thnx_req')
    else:
        sr_form = forms.InitialServiceRequestForm(prefix='sr')
        principal_form = forms.ApplicantFormInitial(prefix='principal')
        dependents_formset = forms.ApplicantFormInitialFormSet(queryset=models.Applicant.objects.none(), prefix='dependents')
    
    return render_to_response('initial_request.html',
                              {'title': 'Welcome',
                               'sr_form': sr_form,
                               'principal_form': principal_form,
                               'dependents_formset': dependents_formset},
                              context_instance=RequestContext(request))

@never_cache
@csrf_protect
@transaction.commit_on_success
def request_do_payment(request, reference_key):
    # Check reference key
    service_request = models.ServiceRequest.objects.get_by_reference_key(reference_key)
    if not service_request:
        return redirect('request_not_found')
    
    # Client can use his/her reference key to check the status of all his requests.
    # If request does not require payment anymore just redirect to request status page
    if service_request.status != models.REQUEST_STATUS_UNCONFIRMED:
        return redirect('request_status', reference_key=reference_key)
    
    if request.method == 'POST':
        request_form = forms.ServiceRequestPaymentForm(request.POST, request.FILES, instance=service_request, prefix='sr')
        consent_formset = forms.ApplicantFormConsentFormSet(request.POST, request.FILES, instance=service_request, prefix='consent_formset')
        
        if request_form.is_valid() and consent_formset.is_valid():
            # Just get new values from form. Will save it later on.
            request_form.save(commit=False)
            
            service_request.status = models.REQUEST_STATUS_ORIGINATED
            service_request.save()
            
            consent_formset.save()
            
            return redirect('thnx_payment')
    else:
        request_form = forms.ServiceRequestPaymentForm(instance=service_request, prefix='sr')
        consent_formset = forms.ApplicantFormConsentFormSet(instance=service_request, prefix='consent_formset')
    
    return render_to_response("payment_form.html", {'title': 'Apply for CAIPS request', 
                                                    'caips_form': request_form,
                                                    'consent_formset': consent_formset},
                              context_instance=RequestContext(request))

def request_not_found(request):
    return render_to_response("request_not_found.html", {'title': 'Request not found'})

def whyneed(request):
    return render_to_response("whyneed.html", {'title': 'Why do you need CAIPS'})

def webest(request):
    return render_to_response("webest.html", {'title': 'We are best'})

def contact(request):
    return render_to_response("contact.html", {'title': 'Contact us'})

def thnx_req(request):
    return render_to_response("thanks_request.html", {'title': 'Thank you'})

def thnx_payment(request):
    return render(request, "thanks_payment.html", {'title': 'Thank you'})

# Agent cabinet

def agent_index(request):
    return redirect("webest")

#def request_detail(request, sr_id):
def request_detail(request, reference_key):
    #service_request = models.ServiceRequest.objects.get(pk=sr_id)
    service_request = models.ServiceRequest.objects.get_by_reference_key(reference_key)
    
    # TODO: check if agent can see this service request
    if not service_request:
        return redirect('request_not_found')
    
    return render_to_response("request_detail.html", {'title': 'Service Request Details', 
                                                      'sr': service_request},
                              context_instance=RequestContext(request)) 

def request_action(request):
    return render_to_response("thanks_payment.html", {'title': 'Thank you'})


def paypal(request, reference_key):

    # What you want the button to do.

    paypal_dict = {
        "custom": reference_key,
        "business": settings.PAYPAL_RECEIVER_EMAIL,
        "amount": settings.PAYPAL_PRICE,
        "currency_code": settings.PAYPAL_CURRENCY_CODE,
        "item_name": "Information request",
        "invoice": str(uuid.uuid1()), # PayPal wants a unique invoice ID
        "notify_url": "%s%s" % (settings.SITE_NAME, reverse('paypal-ipn')),
        "return_url": "%s%s" % (settings.SITE_NAME, reverse('thnx_payment')), #"http://latentforce.dyndns.org/your-return-location/"
        "cancel_return": "%s%s" % (settings.SITE_NAME, reverse('request_not_found')), #"http://latentforce.dyndns.org/your-cancel-location/",
    }

    # Create the instance.
    form = PayPalPaymentsForm(initial=paypal_dict)
    context = {"form": form.sandbox()}
    return render_to_response("paypal.html", context)



